package com.infoauto.opc.gateway.messages.model;


import com.infoauto.opc.gateway.messages.constants.MqttConstants;
import com.infoauto.opc.gateway.messages.handler.MqttListener;
import com.infoauto.opc.gateway.messages.util.SerializeUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

//MQTT协议发送端
public class MqttSender extends MqttAccess {

    public MqttSender(MqttPahoClientFactory clientFactory, String clientId, MqttListener mqttListener) {
        super(clientFactory, clientId, mqttListener);
    }

    //发送消息
    public void publish(String topic, Object message) throws MqttException {
        publish(topic, message, MqttConstants.DEFAULT_QOS);
    }

    private void publish(String topic, Object message, int qos) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(SerializeUtils.serialize(message));
        mqttMessage.setQos(qos);
        mqttMessage.setRetained(true);
        mqttClient.publish(topic, mqttMessage);
    }
}
